const app = require('express')()
const http = require('http').Server(app)
const io = require('socket.io')(http)

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/views/index.html')
})



// socket.emit()  // 触发事件
io.on('connection', function(socket) {
  let username = ''
  socket.on('username', function(user) {
    io.emit('username', user)
    username = user
  })
  socket.on('msg', function(msg) {
    io.emit('msg', msg, username)
  })
  socket.on('writing', function() {
    // 1.广播给所有客户端
    // io.emit('writing', username)
    // 2.广播给除了自己的其他客户端
    socket.broadcast.emit('writing', username)
    // 3.广播给自己
    // socket.emit('writing', username)
  })
  socket.on('disconnect', function() {
    if (username !== '') {
      io.emit('remove', username)
    }
  })
})

http.listen(3000, function() {
  console.log('listen on 3000')
})